package com.hexseek.libretvcloud.controller;


import com.hexseek.libretvcloud.model.R;
import com.hexseek.libretvcloud.model.SearchResult;
import com.hexseek.libretvcloud.model.VideoInfo;
import com.hexseek.libretvcloud.service.SearchDetailService;
import com.hexseek.libretvcloud.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhougb9
 * @version 1.0.0
 * @description TODO
 * @date 2025/5/14 18:31
 * @title SearchController
 */
@RestController
@RequestMapping("/api/search")
public class SearchController {


    @Autowired
    private SearchService searchService;

    @Autowired
    private SearchDetailService detailService;

//    @PostMapping("search")
//    public R<?> search(
//            @RequestBody Map<String, Object> request,
//            @CookieValue(value = "userId", required = false) String userId) {
//
//        String query = (String) request.get("keyword");
//
//        if (query == null || query.isEmpty()) {
//            R.fail("查询参数不能为空");
//        }
//
//        List<SearchResult> results = searchService.search(userId, query);
//
//        return R.ok(results);
//    }


    @GetMapping(path = "/stream", produces = "text/event-stream")
    public SseEmitter searchStream(
            @RequestHeader(value = "userId", required = false) String userId,
            @RequestParam String keyword,
            @RequestParam(required = false, defaultValue = "1") int page) {
        // 使用用户ID或生成默认ID
        String effectiveUserId = userId != null ? userId : "anonymous-" + System.currentTimeMillis();
        return searchService.searchStream(effectiveUserId, keyword, page);
    }

    @PostMapping("detail")
    public R<?> detail(
            @RequestBody Map<String, Object> request,
            @CookieValue(value = "userId", required = false) String userId) {

//        Integer vodId = (Integer) request.get("vodId");
//        Integer proxyId = (Integer) request.get("proxyId");

        String vodIdStr = (String) request.get("vodId");
        Integer vodId = vodIdStr != null ? Integer.valueOf(vodIdStr) : null;

        String proxyIdStr = (String) request.get("proxyId");
        Integer proxyId = proxyIdStr != null ? Integer.valueOf(proxyIdStr) : null;

        List<VideoInfo> results = detailService.detail(userId, vodId, proxyId);

        return R.ok(results);
    }
}
